<template>
  <div id="root">
    <div class="todo-container">
      <div class="todo-wrap">
        <MyHeader @addTodos="addTodos"/>
        <MyList 
        :todos="todos" 
        :itemCheck="itemCheck"
        :itemDelete="itemDelete"
        />
        <MyFooter
        :todos="todos"
        :itemCheckeAll="itemCheckeAll"
        :itemClearAll="itemClearAll"
        />
      </div>
    </div>
  </div>
</template>

<script>

// import Footer from "./components/MyFooter.vue"
// import Header from "./components/MyHeader.vue"
import MyFooter from "./components/MyFooter.vue"
import MyHeader from "./components/MyHeader.vue"

import MyList from "./components/MyList.vue"
/**
 * 取的名字，尽量不要和html的已有标签名重复。
 * 
 */
export default {
    name:"App",
    components:{
      MyFooter,
      MyHeader,
      MyList
    },
    methods: {
      // 数据写在哪里，操作就写在哪里
      addTodos(obj){
        this.todos.unshift(obj)
        //虽然兄弟组件之间无法通信，但是父子之间
        //可以通过，父节点，将方法传递给子组件，子组件调用来获得
      },
      itemCheck(id){
        this.todos.forEach(element => {
          if(element.id===id) //取反
          element.completed = !element.completed
        });
      },
      itemDelete(id){
        this.todos=this.todos.filter(v=>v.id!==id)
      },
      // 全选或者取消勾选
      itemCheckeAll(value){
        //只要直接修改就行
        this.todos.forEach(todo=>todo.completed=value)
      },
      itemClearAll(){
        this.todos=this.todos.filter(todo=>!todo.completed)
      },
      updateTodo(id,value){
        this.todos.forEach(element => {
          if(element.id===id) //取反
          element.title = value
        });
      }
    },
    data(){
      return {
        todos:JSON.parse(
          localStorage.getItem('todos')||[]
        )
      }
    },
    watch:{
      // todos(value){
      //     localStorage.setItem('todos',
      //     JSON.stringify(value))
      // }
      todos:{
        // immediate:true,
        deep:true,//开启深度监视
        handler(newValue,oldValue){
           localStorage.setItem('todos',
          JSON.stringify(newValue))
          }
        }
      
    },
    mounted() {
      this.$bus.$on('updateTodo',this.updateTodo)
    },
    beforeDestroy() {
      this.$bus.$off('updateTodo')
    },
}
</script>

<style scoped>
  /*base*/
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}





</style>